import { modal } from '/shop/store/modal.js';
import $helper from '/shop/helper';
import dayjs from 'dayjs';
import { ref } from 'vue';
import test from '/shop/helper/test.js';
import app from '/shop/api/app';

//smsLogin
//accountLogin
// 打开授权弹框
export function showAuthModal(type = 'accountLogin') {
	let modalStore = modal();
	closeAuthModal();
	console.log('处理modal....');

	setTimeout(() => {
		modalStore.$patch((state) => {
			state.auth = type;
		});
	}, 500);
}

// 关闭授权弹框
export function closeAuthModal() {
	let modalStore = modal();
	modalStore.auth = '';

	// modal().$patch((state) => {
	// 	state.auth = '';
	// });
}

// 打开分享弹框
export function showShareModal() {
	console.log('弹出分享页面');

	let modalStore = modal();
	// $store('modal').$patch((state) => {
	//   state.share = true;
	// 验证
	// });

	modalStore.share = true;
	// modal().$patch((state) => {
	// 	state.share = false;
	// });
}

// 关闭分享弹框
export function closeShareModal() {
	let modalStore = modal();
	// modal().$patch((state) => {
	// 	state.share = false;
	// });

	modalStore.share = false;
}

// 打开快捷菜单
export function showMenuTools() {
	let modalStore = modal();
	// modal().$patch((state) => {
	//   state.menu = true;
	// });
	modalStore.menu = true;
}

// 关闭快捷菜单
export function closeMenuTools() {
	let modalStore = modal();
	// $store('modal').$patch((state) => {
	//   state.menu = false;
	// });

	modalStore.menu = false;
}

// 发送短信验证码  60秒
export function getSmsCode(event, mobile = '', captchaVerification = '', callback = '') {
	const modalStore = modal();
	const lastSendTimer = modalStore.lastTimer[event];

	if (typeof lastSendTimer === 'undefined') {
		$helper.toast('短信发送事件错误');
		return;
	}

	const duration = dayjs().unix() - lastSendTimer;
	const canSend = duration >= 60;

	if (!canSend) {
		$helper.toast('请稍后再试');
		return;
	}

	if (!test.mobile(mobile)) {
		$helper.toast('手机号码格式不正确');
		return;
	}

	// 发送验证码 + 更新上次发送验证码时间
	app.sendSms({
		mobile,
		event,
		captchaVerification,
	}).then((res) => {
		if (res.code === '0') {
			// modalStore.$patch((state) => {
			//   state.lastTimer[event] = dayjs().unix();
			// });
			modalStore.lastTimer[event] = dayjs().unix();
			callback();
		}
	});
}

// 获取短信验证码倒计时 -- 60秒
export function getSmsTimer(event, mobile = '') {
	const modalStore = modal();
	const lastSendTimer = modalStore.lastTimer[event];

	if (typeof lastSendTimer === 'undefined') {
		$helper.toast('短信发送事件错误');
		return;
	}

	const duration = ref(dayjs().unix() - lastSendTimer - 60);
	const canSend = duration.value >= 0;

	if (canSend) {
		return '获取验证码';
	}

	if (!canSend) {
		setTimeout(() => {
			duration.value++;
		}, 1000);
		return -duration.value.toString() + ' 秒';
	}
}

// 记录广告弹框历史
export function saveAdvHistory(adv) {
	const modalStore = modal();
	if (!modalStore.advHistory.includes(adv.src)) {
		modalStore.advHistory.push(adv.src);
	}
}
